/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.frontendproject.webservice;

import com.inspur.edp.web.common.customexception.WebCustomException;
import com.inspur.edp.web.common.entity.ResultCode;
import com.inspur.edp.web.common.entity.ResultMessage;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.common.logger.WebLogger;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.common.utility.ResourceLocalizeUtil;
import com.inspur.edp.web.common.utility.StringUtility;
import com.inspur.edp.web.frontendproject.constant.I18nMsgConstant;
import com.inspur.edp.web.frontendproject.FrontendProjectManager;
import com.inspur.edp.web.frontendproject.build.FrontendProjectBuild;
import com.inspur.edp.web.frontendproject.deploy.FrontendProjectDeployer;
import com.inspur.edp.web.frontendproject.entity.ChosenFormList;
import com.inspur.edp.web.frontendproject.entity.IdeConfigEntity;
import com.inspur.edp.web.frontendproject.entity.VueFormReq;
import com.inspur.edp.web.frontendproject.generate.FrontendProjectGenerate;
import com.inspur.edp.web.frontendproject.projectinfo.ProjectInfoManager;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.Arrays;

/**
 * description:
 *
 * @author Noah Guo
 * @date 2021/01/15
 */
public class FrontendProjectWebServiceImpl implements FrontendProjectWebService {

    @Override
    public boolean isFrontendProject(String projectPath) {
        ProjectInfoManager projectInfoManager= SpringBeanUtils.getBean(ProjectInfoManager.class);
        return projectInfoManager.isFrontendProject(projectPath);
    }

    @Override
    public void resolveFrontendProject(String projectPath) {
        FrontendProjectManager.getInstance().resolveFormMetadatas(projectPath);
    }

    @Override
    public void generateFrontendProject(String projectPath) {
        FrontendProjectGenerate.generateFrontendProject(projectPath);
    }

    @Override
    public ResultMessage buildFrontendProject(String projectPath) {
        try {
            return FrontendProjectBuild.buildFrontendProject(projectPath, false);
        } catch (WebCustomException ex) {
            if (ex.getCause() != null && ex.getCause() instanceof RuntimeException) {
                RuntimeException causeException = (RuntimeException) ex.getCause();
                return ResultCode.failure(causeException.getMessage());
            }
        } catch (Exception ex) {
            return ResultCode.failure(ex.getMessage() + Arrays.toString(ex.getStackTrace()));
        }
        return ResultCode.success();
    }

    @Override
    public void resolveAndGenerateFrontendProject(String projectPath) {
        FrontendProjectManager.getInstance().ResolveAndGenerateFrontendProject(projectPath);
    }

    @Override
    public ResultMessage resolveAndGenerateAndBuildFrontendProject(String projectPath) {
        try {
            return FrontendProjectManager.getInstance().resolveAndGenerateAndBuildFrontendProject(projectPath);
        } catch (Exception ex) {
            if (ex instanceof WebCustomException) {
                if (ex.getCause() != null && ex.getCause() instanceof RuntimeException) {
                    RuntimeException causeException = (RuntimeException) ex.getCause();
                    return ResultCode.failure(causeException.getMessage());
                }
            }
            return ResultCode.failure(ex.getMessage() + Arrays.toString(ex.getStackTrace()));
        }
    }

    @Override
    public void deployFrontendProject(String projectPath) {
        FrontendProjectDeployer.deployFrontendProject(projectPath);
    }

    @Override
    public void oneKeyDeployFrontendProject(String projectPath) {
        FrontendProjectManager.getInstance().resolveAndGenerateAndBuildFrontendProject(projectPath);
        FrontendProjectDeployer.deployFrontendProject(projectPath);
    }

    /**
     * 使用babel编译前端工程并部署。
     */
    @Override
    public void babelBuildAndDeploy(String projectPath, String formCode) {
        ChosenFormList buildFormList = ChosenFormList.getNewInstance();
        if (!StringUtility.isNullOrEmpty(formCode)) {
            buildFormList.add(formCode);
        }
        FrontendProjectManager.getInstance().babelBuildAndDeploy(projectPath, buildFormList);
    }

    /**
     * 解析类型表单的预览动作
     * 理论上只输出该表单依赖项即可
     *
     * @param dynamicParameter
     */
    @Override
    public ResultMessage generateFrontendProjectWithDynamic(FormDynamicParameter dynamicParameter) {
        try {
            return FrontendProjectManager.getInstance().resolveAndGenerateFrontendProjectWithDynamic(dynamicParameter);
        } catch (WebCustomException ex) {
            if (ex.getCause() instanceof RuntimeException) {
                RuntimeException causeException = (RuntimeException) ex.getCause();
                return ResultCode.failure(causeException.getMessage());
            }
        } catch (Exception ex) {
            return ResultCode.failure(ex.getMessage() + Arrays.toString(ex.getStackTrace()));
        }
        return ResultCode.success();
    }

    @Override
    public ResultMessage<IdeConfigEntity> getProjectConfig() {
        ResultMessage<IdeConfigEntity> resultMessage = ResultCode.success();
        String currentServerRTPath = FileUtility.getServerRTPath();
        String configFilePath = FileUtility.combine(FileUtility.combine(currentServerRTPath, "config", "platform"), "dev", "main", "ide_config.json");
        IdeConfigEntity ideConfigEntity = IdeConfigEntity.init();

        if (FileUtility.exists(configFilePath)) {
            try {
                String strFileContent = FileUtility.readAsString(configFilePath);
                ideConfigEntity = SerializeUtility.getInstance().deserialize(strFileContent, IdeConfigEntity.class);
            } catch (Exception ex) {
                WebLogger.Instance.error(ResourceLocalizeUtil.getString(I18nMsgConstant.WEB_FRONT_PROJECT_MSG_0003));
                if (ideConfigEntity == null) {
                    ideConfigEntity = IdeConfigEntity.init();
                }
            }
        }
        resultMessage.setData(ideConfigEntity);
        return resultMessage;
    }
}

